package com.example.user.service;
import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.example.pojo.GdUser;
import com.example.service.RpcTokenService;
import com.example.utils.DateUtils;
import com.example.utils.MD5;
import com.example.utils.RedisUtils;
import com.example.vo.TokenVO;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import static com.example.utils.Constants.Redis_Expire.REPLACEMENT_DELAY;
import static com.example.utils.Constants.Redis_Expire.REPLACEMENT_PROTECTION_TIMEOUT;

@Component
@Service(interfaceClass=RpcTokenService.class)
public class RpcTokenServiceImpl implements RpcTokenService  {

	@Resource
    private RedisUtils redisUtils;

	private String tokenPrefix = "token:";
	/***
	 * @param user 用户信息
	 * @return Token格式<br/>
	 * 	PC：“前缀PC-USERCODE-USERID-CREATIONDATE-RONDEM[6位]” 
	 *  <br/>
	 *  Android：“前缀ANDROID-USERCODE-USERID-CREATIONDATE-RONDEM[6位]”
	 */
	@Override
	public String generateToken(GdUser user) {
        StringBuilder sb = new StringBuilder();
        sb.append(tokenPrefix);
        sb.append(MD5.getMd5(user.getUsercode(),32) + "-");
        sb.append(user.getGd() + "-");
        sb.append(new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()));
        return sb.toString();
	}


	/**
	 * 验证token，并判断token是否符合置换条件
	 * @param agent
	 * @param token
	 * @return
	 * @throws Exception
	 */
	@Override
	public TokenVO verifyToken(String agent, String token) throws Exception {
        // 验证旧token是否有效
		String value = redisUtils.getValue(token);
		if(value==null){
			throw new Exception("token不存在，请重新认证！");
		}

		String[] tokenMessger = token.split("-");

		Long generate = DateUtils.getDateMillisecond(tokenMessger[3],"yyyyMMddHHmmss");

		Long passed = Calendar.getInstance().getTimeInMillis()- generate;

		/**
		 * 判断是否置换token，若在保护期内则不置换，返回老token
		 */
		if(passed < REPLACEMENT_PROTECTION_TIMEOUT){
			return new TokenVO(token,generate+REPLACEMENT_PROTECTION_TIMEOUT,generate);
		}
		GdUser user = JSON.parseObject(value, GdUser.class);
		/**
		 * 返回新token1
		 */
		String newToken = null;
		if(redisUtils.getResidueTime(token)>0 || redisUtils.getResidueTime(token)==-1){
			newToken =  this.generateToken(user);
			redisUtils.set(token,value, REPLACEMENT_DELAY);
		}else {
			throw new Exception("过期时间异常，无法置换！");
		}
		return new TokenVO(newToken, Calendar.getInstance().getTimeInMillis()+REPLACEMENT_PROTECTION_TIMEOUT,Calendar.getInstance().getTimeInMillis());
	}
}
